<?php

class discounts_model extends MY_Model
{

    function __construct()
    {
        parent::__construct();
        $this->table='discounts';

    }

    function find_all_rules($discounts_ID)
    {
        $q="
            SELECT * FROM rules
            WHERE discounts_ID =  $discounts_ID
            ";

        $res=$this->db->query($q)->result_array();
        return $res;

    }

    function find_all_rules_adults($discounts_ID, $nr_adults)
    {
        $q="
            SELECT * FROM rules
            WHERE discounts_ID = $discounts_ID and nr_adults = $nr_adults
            ";

        $res=$this->db->query($q)->result_array();

        return $res;

    }

    // return rules with  minimal number of adults
    function find_rules_min_nr_adults($discounts_ID)
    {
        $q="SELECT *
                FROM rules
                WHERE nr_adults = (
                    SELECT MIN( nr_adults )
                    FROM rules
                    WHERE discounts_id = $discounts_ID)
                AND discounts_ID = $discounts_ID
                ";
        $res=$this->db->query($q)->result_array();

        return $res;
    }

    function delete_rules($discounts_ID, $nr_adults)
    {
        $q="
            DELETE FROM rules
            WHERE discounts_ID = $discounts_ID and nr_adults = $nr_adults
            ";

        $res=$this->db->query($q);
        return $res;

    }

    function find_discount_rule($discounts_ID, $age)
    {
        if($age == 0):
            return 100;
        endif;

        $q="
            SELECT * FROM rules
            WHERE discounts_ID =  ?
            AND
            ( $age  > `from` AND  $age <=`to`)
            ORDER BY `from` DESC
            LIMIT 1
            ";

        $res=$this->db->query($q, array($discounts_ID))->row_array();

        //log_message('error', $this->db->last_query());

        if(isset($res['discount_percent']))
            return $res['discount_percent'];
        else
            return 0;

    }

    function find_discount_rule_nr_adults($discounts_ID, $age, $nr_adults)
    {
        if($age == 0):
            return 100;
        endif;

        // TODO will return rule only if nr_adults is same as specified
        $q="
            SELECT * FROM rules
            WHERE discounts_ID = $discounts_ID
            AND
            nr_adults = $nr_adults
            AND
            ( $age  > `from` AND  $age <=`to`)
            ORDER BY `from` DESC
            LIMIT 1
            ";

        $res=$this->db->query($q, array($discounts_ID))->row_array();

        //log_message('error', $this->db->last_query());

        if(isset($res['discount_percent']))
            return $res['discount_percent'];
        else
            return 0;

    }

}

?>
